package com.stock.stockana.ui.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.stock.publiclib.model.UserService;
import com.stock.publiclib.utils.DesUtils;
import com.stock.publiclib.utils.StringUtil;
import com.stock.stockana.R;
import com.stock.stockana.StockCenter;
import com.stock.stockana.beans.ResponseBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.constants.PublicConstants;
import com.stock.stockana.events.network.LoginInEvent;
import com.stock.stockana.requests.EasyLoginIn;

import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

/**
 * ---------------------------------------------------
 * Description: 打开应用后,最先启动的欢迎activity
 * Author: ljgsonx
 * Belong to: com.example.administrator.alldemos
 * Time: 2015/12/8 16:13
 * ---------------------------------------------------
 */
public class WelcomeActivity extends AppCompatActivity {

    private final static String TAG = "WelcomeActivity";

    private long exitTime = 0;

    @Bind(R.id.loginBtn)
    Button loginBtn;
    @Bind(R.id.registerBtn)
    Button registerBtn;
    @Bind(R.id.easyRegisterBtn)
    Button easyRegisterBtn;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!StringUtil.isBlank(StockCenter.getUserDB().getAccessToken())) {
            startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
            finish();
            return;
        }
        setContentView(R.layout.welcome_layout);
        ButterKnife.bind(this);
        //沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WelcomeActivity.this, SignInActivity.class));
                overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
            }
        });
        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WelcomeActivity.this, SignUpActivity.class));
                overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
            }
        });
        easyRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneId = StockCenter.getDeviceUUID();
                EasyLoginIn easyLoginIn = EasyLoginIn.build().setPhoneId(phoneId);
                StockCenter.doReq(easyLoginIn);
                showProgress("正在登录...");
            }
        });
        EventBus.getDefault().register(this);
    }

    @Subscribe
    public void onEventMainThread(LoginInEvent event) {
        final ResponseBean rb = event.getmResponseBean();
        if (rb.getRespCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            String accessToken = rb.getAccessToken();
            String uuid = null;
            try{
                String result = new DesUtils(DesUtils.strDefaultKey).decrypt(accessToken);
                String str[] = result.split(",");
                uuid = str[0].trim();
                uuid = uuid.replace("-", "");
                Log.d(TAG, "start registering uuid to JPush:" + uuid);
            }catch(Exception e) {
                Log.d(TAG, "解析access-token出错");
                e.printStackTrace();
            }
            JPushInterface.setAlias(this, uuid, new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    if (i == PublicConstants.JPUSH_RESPONSE_CODE_OK) {
                        stopProgress();
                        showProgress("登录成功,正在跳转...");
                        Log.d(TAG, "JPush set alias success!");
                        StockCenter.getUserDB().saveToken(rb.getAccessToken());
                        UserService userService = StockCenter.getUserDB();
                        userService.saveKeyValue("tempUserName", "临时用户");
                        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        overridePendingTransition(R.anim.in_from_right,R.anim.out_from_left);
                        finish();
                        return;
                    } else if (i == PublicConstants.JPUSH_RESPONSE_CODE_TIMEOUT) {
                        Log.d(TAG, "JPush set alias timeout");
                    } else {
                        Log.d(TAG, "JPush set alias unknown error:"+i);
                    }
                    Toast.makeText(WelcomeActivity.this, "网络连接错误,请重试!", Toast.LENGTH_LONG).show();
                }
            });
        }else if(rb.getRespCode() == NetWorkConstants.RESPONSE_CODE_NETWORK_ERROR){
            stopProgress();
            Log.d(TAG, rb.getErrorMsg());
            Toast.makeText(this, "网络连接错误,请检查网络!", Toast.LENGTH_LONG).show();
        }else{
            stopProgress();
            Log.d(TAG, rb.getErrorMsg());
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_LONG).show();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    /**
     * Description: 设置默认字体
     * Author: ljgsonx
     * Time: 2016/2/24 13:58
     */
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    public void showProgress(final String title) {
        if (!isProgress()) {
            ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setIndeterminateDrawable(getResources().getDrawable(com.stock.publiclib.R.drawable.process_dialog_clockwise));
            progressDialog.setCancelable(true);
            if (!TextUtils.isEmpty(title)) {
                progressDialog.setMessage(title);
            }
            progressDialog.show();
            this.progressDialog = progressDialog;
        }
    }

    public void stopProgress() {
        if (isProgress()) {
            progressDialog.dismiss();
        }
    }

    public boolean isProgress() {
        return progressDialog != null && progressDialog.isShowing();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序!", Toast.LENGTH_LONG).show();
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }
}
